package com.ycz.sas.jgen.ui;

import java.awt.Color;
import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;

import com.kingdee.eas.base.license.ModuleLicenseInfo;
import com.kingdee.eas.base.license.file.EASLicenseReader;
import com.kingdee.eas.base.license.file.License;
import com.kingdee.eas.base.license.file.LicenseFileErrorException;
import com.kingdee.eas.base.license.file.Util;
import com.ycz.sas.jgen.domain.TableModel;

public class LicenceUI extends JDialog{
	
	public SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private JButton btnLicence;
	private JTextField txtLicenceFile;
	private JTextField dateto;
	private JButton btnAll100;
	private Util util;
	private TableModel model;
	private JButton btnViewLicence;
	private JTable table;
	private JButton btnGenLicence;
	
	public LicenceUI(JFrame owner, boolean modal) {
		super(owner, modal);
		
		initLayout();
	}
	
	@Override
	public String getTitle() {
		return "Licence Tool";
	}
	
	protected void initLayout(){
		setSize(500, 600);
		setResizable(false);
		
		JPanel panel = new JPanel();
		panel.setBackground(Color.white);
		add(panel, "Center");
		btnLicence = new JButton("License");
		txtLicenceFile = new JTextField(30);
		JLabel ldateto = new JLabel(" License Date To ");
		dateto = new JTextField(15);
		btnAll100 = new JButton("All to 100");
		model = new TableModel(new String[]{ "Module", "Number", "UntilDate" });
		table = new JTable(model);
		setTableType(table);
		JScrollPane s_pan = new JScrollPane(table);
		s_pan.setForeground(Color.white);
		btnViewLicence = new JButton("View");
		btnGenLicence = new JButton("Generate");
		panel.add(btnLicence);
		panel.add(txtLicenceFile);
		panel.add(ldateto);
		panel.add(dateto);
		panel.add(btnAll100);
		panel.add(s_pan);
		panel.add(btnViewLicence);
		panel.add(btnGenLicence);
		
		btnLicence.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				actionLicence();
				actionViewLicence();
			}
		});
		btnViewLicence.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				actionViewLicence();
			}
		});
		btnGenLicence.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				actionGenLicence();
			}
		});
		
		btnAll100.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				int count = model.getRowCount();
				for (int i = 0; i < count; i++) {
					model.setValueAt("100", i, 1);
				}
			}
		});
		
		Document docdateto = dateto.getDocument();
		docdateto.addDocumentListener(new DocumentListener() {
			
			@Override
			public void removeUpdate(DocumentEvent arg0) {
				int count = model.getRowCount();
				for (int i = 0; i < count; i++) {
					model.setValueAt(dateto.getText(), i, 2);
				}
			}
			
			@Override
			public void insertUpdate(DocumentEvent arg0) {
				int count = model.getRowCount();
				for (int i = 0; i < count; i++) {
					model.setValueAt(dateto.getText(), i, 2);
				}
			}
			
			@Override
			public void changedUpdate(DocumentEvent arg0) {
				
			}
		});
	}

	public void setTableType(JTable table){
		table.setGridColor(Color.lightGray);
		table.getColumnModel().getColumn(0).setPreferredWidth(100);
		table.getColumnModel().getColumn(1).setPreferredWidth(10);
		table.getTableHeader().setBackground(Color.getHSBColor(221, 221, 240));
	}
	
	private void actionLicence(){
		FileDialog fc = new FileDialog(this, "Choose License File");
		fc.show();
		String filename = fc.getDirectory() + fc.getFile();
		System.out.println(filename);
		if (!"nullnull".equals(filename)) {
			txtLicenceFile.setText(filename);
			removeAll();
		}
	}
	
	private void actionViewLicence(){
		removeAll();
		List<ModuleLicenseInfo> data = getData();
		if (data == null)
			return;
		for (int i = 0; i < data.size(); i++) {
			ModuleLicenseInfo module = data.get(i);
			String utilDate = null;
			if(module.getExpireDate() != null)
				utilDate = sdf.format(module.getExpireDate());
			if(utilDate == null)
				model.addRow(new String[]{module.getModuleName(), 
						String.valueOf(module.getLicenseNum()), String.valueOf(module.getDuration())});
			else
				model.addRow(new String[]{module.getModuleName(), String.valueOf(module.getLicenseNum()), utilDate});
		}
		table.updateUI();
	}
	
	private void actionGenLicence(){
		util = new Util();
		util.readLicense(txtLicenceFile.getText());
		if (model.getRowCount() <= 0) {

		} else {
			String licenseType = updateLicenceType();
			util.modifyLicenseType(licenseType);
		}
		
		Date today = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String initialDate = util.toCode(sdf.format(today));
		util.modifyInitialDate(initialDate);
		
		// 限时licence的过期日期
		if(util.getString("ValidityExpireDate") != null && util.getString("ValidityExpireDate") .length() >= 0 ){
			String validityExpireDate = util.toCode(dateto.getText());
			util.modifyValidityExpireDate(validityExpireDate);
		}

		if (dateto.getText() == null || "".equals(dateto.getText())) {

		} else {
			String expireDate = util.toCode(dateto.getText());
			util.modifyExpireDate(expireDate);
		}
		removeAll();
//		util.backup();
	}
	
	public void removeAll() {
		dateto.setText(null);
		model.removeRows(0, model.getRowCount());
		table.updateUI();
	}

	public List<ModuleLicenseInfo> getData() {
		EASLicenseReader easreader = new EASLicenseReader();
		try {
			easreader.readLicenseFromFile(txtLicenceFile.getText());
		} catch (LicenseFileErrorException e) {
//			e.printStackTrace();
			JOptionPane.showMessageDialog(this, "No LicenseFile or LicenseFile Error!");
		}
		License li = easreader.getLicenseFileRefrence();
		if (li == null)
			return null;
		dateto.setText(sdf.format(li.getExpireDate()));
		List<ModuleLicenseInfo> infolist = li.getModuleDetails();
		return infolist;
	}

	public String updateLicenceType() {
		String after = "";
		List<String> numList = new ArrayList<String>();
		List<String> dateList = new ArrayList<String>();
		for (int i = 0; i < model.getRowCount(); i++) {
			numList.add(Util.toCode((String) model.getValueAt(i, 1)));
			dateList.add(Util.toCode((String) model.getValueAt(i, 2)));
		}
		String before = util.getString("LicenseType");
		String[] allorg = before.split("0F56");
		for (int i = 0; i < allorg.length; i++) {
			after += (i == 0) ? "" : "0F56";
			String[] detail = allorg[i].split("1052");
			for (int j = 0; j < detail.length; j++) {
				after += (j == 0) ? "" : "1052";
				boolean isDateformat = dateList.get(i).length() == 76;
				after += (j == 2) ? numList.get(i): (j == 3 && isDateformat) ? dateList.get(i)
						: detail[j];
			}
		}
		return after;
	}
	
	
}
